<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="[
          { name: 'box-base', title: '采购信息' },
          { name: 'box-dtl', title: '采购明细' },
        ]"
      />
    </div>

    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly">
        <template #content>
          <div id="box-base" class="box-title">采购信息</div>
          <customFormItem
            label="申请科室" name="deptName" :parent="_self" :form="form"
            @focusTo="$refs.deptName.focus()"
            :type="constCommon.formItemType.slot.name"
          >
            <template #content>
              <deptSelect
                v-model="form.deptId"
                :valueDisplay="form.deptName"
                @change="deptIdChange"
                ref="deptName"
                :disabled="propReadonly"
              />
            </template>
          </customFormItem>

          <customFormItem
            label="需求单号"
            name="busKey"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.staticHtml.name"
            :config="{defaultValue: '自动获取'}"
          />
          <customFormItem
            label="需求日期"
            name="busDate"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.datePicker.name"
            :config="{defaultValue: '自动获取'}"
            disabled
          />
          <customFormItem
            label="请领人"
            name="busUser"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.staticHtml.name"
            :config="{defaultValue: '自动获取'}"
          />
          <customFormItem
            label="申请仓库"
            name="applyWarehouseName"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.staticHtml.name"
            :config="{ defaultValue: '自动获取'}"
          />
          <customFormItem
          label="计划类型"
          name="demandType"
          :parent="_self"
          :form="form"
          :type="constCommon.formItemType.selectDict.name"
          :config="{dictType: constCommon.dictType.demandType}"
          :disabled="!cpIsStart"
          />
          <customFormItem
            label="要求到货日期"
            name="dateLates"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.datePicker.name"
            :config="{defaultValue: '自动获取'}"
            :disabled="!cpIsStart"
          />
          <customFormItem
            label="备注"
            name="remark"
            :parent="_self"
            :form="form"
          />

        </template>
      </customForm>

      <div id="box-dtl" class="box-title">采购明细</div>
      <data-view
        propViewKey="dept_demand_item"
        :propInitData="form"
        ref="childDataView"
        :propParentPage="_self"
        :propAutoFetchData="false"
        :propHideFlowSelect="true"
        @edit-input="editInput"
        @extra-button-click="extraButtonClick"
        :propFlowKey="propParent.propFlowKey"
        :propFlagApply = "true"
        :propLoadEvery = "true"
        :propCheckFlowParam="getCheckFlowParam()"
        class="data-view-inlinebtn"
        @customSelectFocus="customSelectFocus"
        @afterTableDataChange="afterTableDataChange"
        :propFilterBtn="propFilterBtn"
        :propNoEditRow="true"
        :propBeforeClick="propBeforeClickDtl"
      >
      </data-view>
    </div>
  </div>
</template>
<script>
/*eslint-disable*/
import customAnchor from '@/components/custom/form/customAnchor.vue'
import deptSelect from '@/components/custom/bus/select/deptSelect.vue'

export default {
  data() {
    return {
      form: {},
      viewData: {},
    }
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object,
    propFlowKey: String,
    propParentPage: Object,
    propParam: Object
  },
  components: {
    deptSelect,
    customAnchor
  },
  computed: {
    cpCountDtl() {
      if (!this.form.countDtl) {
        return 0
      }
      return this.form.countDtl
    },
    // 是否是开始
    cpIsStart() {
      return strings.defaultString(this.form.flowStatus, 'start') == 'start'
    }
  },
  created() {
    let that = this
    this.$emit('event-register', {
      validate: (callback) => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        console.log('this.form', this.form)
        if (!this.form.id) {
          this.$set(this.form, 'busUser', this.utils.getCurrentUser().name)
          this.$set(this.form, 'busDate', new Date().format(this.dates.defaultDatePattern))
          this.$set(this.form, 'deptId', this.utils.getCurrentUser().deptId)
          this.$set(this.form, 'deptName', this.utils.getCurrentUser().deptName)
          this.$set(this.form, 'dateLates', this.dates.getDateAfterDays(3))
          this.$set(this.form, 'demandType', 'normal')
          this.$set(this.form, 'refTable', 'SAFE_STOCK')
          this.$set(this.form, 'applyWarehouseId', this.utils.getCurrentWarehouse().warehouseId)
          this.$set(this.form, 'applyWarehouseName', this.utils.getCurrentWarehouse().warehouseName)
        }
        this.fetchChildData()
      },
      afterSave: () => {
      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (valueTO, button, buttonKey) => {
        if (that.form.countDtl == 0) {
          this.utilMessage.error('采购明细为空，不允许提交')
          return false
        }
        return true
      },
      afterFlow: (valueTo, thatParam, buttonKey) => {
        //提交、审核、作废的因为更新了明细状态，所以进行刷新
        if (buttonKey =='pass' || buttonKey =='demand_submit' || valueTo =='start'){
          that.fetchChildData()
        }
      },
      beforeClose: () => {
        return true
      },
      async afterClick(button, data, viewForm) {
        let {key: buttonKey} = button
        if (buttonKey == 'preview') {
          let param = {
            'that': that, //当前调用对象
            configList: [ //打印配置，可以多个
              {
                //打印配置
                printBusType: 'demand', //打印业务类型，来源print_template.bus_type，同constPrint.busKey
                //主单据数据或者数据查询配置
                formData: that.form, //数据对象
                formDataId: that.form.id,
              }
            ]
          }
          global.utilPrint.openFormPrint(param)
        }
      }
    })
  },
  methods: {
    // 科室选择
    deptIdChange(item) {
      this.$set(this.form, 'deptId', item.id)
      this.$set(this.form, 'deptName', item.name)
    },

    //行编辑普通input框的修改事件，比如修改耗材包的数量后自动更新基本单位的数量
    editInput({row, column}) {
      if (column.property == 'packageQty') {
        this.$set(row, 'skuQty', this.utilNum.toFixed(row.packageRate * row.packageQty))
        this.$set(row, 'amount', this.utilNum.toFixed(row.skuPrice * row.skuQty))
      }
    },

    getCheckFlowParam() {
      return this.utils.getCheckFlowParam(this)
    },

    fetchChildData() {
      let newWrapper
      if (this.form.id) {
        newWrapper = this.$newWrapper().eq('demandId', this.form.id) //加上过滤作废的请领明细条件
      } else {
        newWrapper =  this.$newWrapper().ne(1, 1)
      }
      this.$refs.childDataView.setQueryWrapper(newWrapper)
    },

    // 扩展按钮
    extraButtonClick({button, data, index,para}) {
      let { key: buttonKey } = button
      console.log('buttonKey===', buttonKey)
      if (buttonKey === 'chosePackage') { //选择模板
        this.utilSelect.matrPackTempletMore(
        this.packSelect,
        this.form.deptId,
        this.constCommon.dictType.tempTypeDemand)
      }
    },

    saveBatchPackage(rows, isLoadForm) {
      //批量添加
      this.utilVue.loadShow(true)
      this.$ajax
        .post('/dept/demandItem/saveBatchPackage', rows)
        .then(resp => {
          if (resp.code == 0) {
            this.utilMessage.success(resp.msg)
            if (isLoadForm) {
              this.afterTableDataChange()
            }
            this.fetchChildData()
          }
          this.utilVue.loadHide()
        })
    },

    // 模板选择后
    packSelect(rows, refName) {
      let rowsSave = []
      for (let i = 0; i < rows.length; i++) {
        rowsSave.push(rows[i])
        let childCheckedList = rows[i].childData.filter(ob => ob.checked && ob.checked == true)
        //如果子表格没有任何选中，但是因为主数据选中了，就添加所有的
        if (childCheckedList == null || childCheckedList.length < 1) childCheckedList = rows[i].childData
        if (childCheckedList != null) {
          let matrIdList = []
          childCheckedList.forEach(ob => matrIdList.push(ob.matrId))
          rowsSave[i].packTempletMatrIds = matrIdList.join(',')
        }
        rowsSave[i].demandId = this.form.id
      }

      //主单据未保存
      if(this.propParent.cpFormNew) {
        this.propParent.ocAsynSaveViewForm(() => {
          this.saveBatchPackage(rowsSave, true)
        })
        return
      }
      this.saveBatchPackage(rowsSave, true)
    },


    customSelectFocus(column, row) {
      // 包装名称
      if (column.name == 'packageUnit') {
        if (this.strings.isBlank(row.matrId)) {
          this.utilMessage.warning('请先选择商品')
          return
        }
        this.utilSelect.matrUnit(this.packageUnitSelect, row.matrId, true)
      }
    },
    // 商品选择后
    matrSelect(rows, refName) {
      //主单据未保存
      if(this.propParent.cpFormNew) {
        this.propParent.ocAsynSaveViewForm(() => {
          this.saveBatchItem(rows, true)
        })
        return
      }
      this.saveBatchItem(rows, true)
    },
    // 批量保存明细
    saveBatchItem(rows, isLoadForm) {
      this.utilVue.loadShow(true)
      let rowsSave = []
      for (let i = 0; i < rows.length; i++) {
        rowsSave.push(rows[i])
        rowsSave[i].demandId = this.form.id
        if (rows[i].matrBaseType)
          rowsSave[i].baseType = rows[i].matrBaseType
        if (rows[i].name) rowsSave[i].matrName = rows[i].name
        if (rows[i].spec) rowsSave[i].matrSpec = rows[i].spec
      }
      this.$ajax.post('/dept/demandItem/saveBatchForPurchaseDemand', rowsSave).then((resp) => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          this.utilMessage.success(resp.msg)
          this.fetchChildData()
          this.form.countDtl = rows.length
          if (isLoadForm) {
            this.afterTableDataChange()
          }
        }
      })
    },

    // 单位选择后
    packageUnitSelect(row, refName) {
      // packageQty 包装数量
      // 当前选中行
      let currentRow = this.$refs.childDataView.getCurrentRow()
      this.$set(currentRow, 'packageUnit', row.unit)
      this.$set(currentRow, 'packageRate', row.packageRate)
      this.$set(currentRow, 'skuQty', this.utilNum.toFixed(row.packageRate * currentRow.packageQty))
      this.$set(currentRow, 'amount', this.utilNum.toFixed(currentRow.skuPrice * currentRow.skuQty))

      console.log('currentRow', currentRow)
  },

    // 明细 新增、删除、修改后调用
    afterTableDataChange() {
      console.log('afterTableDataChange')
      this.utils.refreshRefs(this)
    },

     // 过滤显示按钮
     propFilterBtn(btnList) {
      // 只读时
      if (this.propReadonly) {
        return btnList.filter(btn => !['chosePackage'].includes(btn.code))
      }
      return btnList
    },
    // 列表添加按钮
    propBeforeClickDtl(button, formData , rowData, that) {
      //列表添加按钮 其他入库
      if (button.key == 'vb-add') {
        this.utilSelect.matrMoreForDept(this.matrSelect,
          this.form.deptId,
          this.form.applyWarehouseId,
          'dept_demand_item',
          'demand_id',
          this.form.id,
          null,
          this.constCommon.dictType.demandType
        )
        return false
      }


      return true;
    },

  }
}
</script>
